package com.alvinlkk.basic.chapter21;

import java.util.concurrent.TimeUnit;

// join 等待一段时间直到第二个线程结束才继续执行
public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("Sleepy", 1);
        Sleeper grummy = new Sleeper("Grumpy", 2);
        
        Joiner dopey = new Joiner("dopey", sleepy);
        Joiner doc = new Joiner("Doc", grummy);
        grummy.interrupt();
    }
}

class Sleeper extends Thread {
    private int duration;
    
    public Sleeper(String name, int sleepTime) {
        super(name);
        duration = sleepTime;
        start();
    }
    
    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            System.out.println(getName() + "was interrupted. " + "isInterrupted(): " + isInterrupted());
            return ;
        }
        System.out.println(getName() + " has awakened");
    }
}

class Joiner extends Thread {
    private Sleeper sleeper;
    
    public Joiner(String name, Sleeper sleeper) {
        super(name);
        this.sleeper = sleeper;
        start();
    }
    
    @Override
    public void run() {
        try {
            sleeper.join();
        } catch (InterruptedException e) {
            System.out.println("Interruptted");
            e.printStackTrace();
        }
        System.out.println(getName() + " join completed");
    }
}